#include "resourcemanager.h"
#include <fmod.h> 
#include <fmod.hpp>
#include <string>

#include <cstring>
#include <iostream>
#include "soundmanager.h"
#include "boost/shared_ptr.hpp"

namespace core
{

    // static variables
    ResourceManager*   ResourceManager::m_Instance = NULL;

    // singelton access
    ResourceManager*   ResourceManager::GetInstance()
    {
        if( ResourceManager::m_Instance )
            return( ResourceManager::m_Instance );

        ResourceManager::m_Instance = new ResourceManager();
        return( ResourceManager::m_Instance );
    }


    //=====================
    // AddResource
    //! Add a resource to the manager.\n
    //! Will throw if the resource you try to add already exists and are valid.
    //=====================
    void ResourceManager::AddResource( const std::string& p_Name, ResourcePtr p_Resource )
    {
        ResourceSet::iterator found = m_Resources.find( p_Name );
        if( found != m_Resources.end() )
        {
            ResourceWeakPtr wp = found->second;
            if( !wp.expired() )
						{
								int i = 34242;
                //THROW_EXCEPTION( "Cannot overwrite a valid existing resource.", p_Name );
						}
        }

        // set the correct name for the resource.
        p_Resource->SetResourceName( p_Name );

        ResourceWeakPtr wp_store( p_Resource );
        m_Resources[p_Name] = wp_store;

				
				
    }


    //=====================
    // GetResource()
    //! Will search in the cache for a resource with the name p_Name.\n
    //! if it finds it will return it. Else it will return a empty ResourcePtr.\n
    //! NOTE: it will also make sure that if the resource is there its valid before\n
    //! returning.
    //=====================
    ResourcePtr ResourceManager::GetResource( const std::string& p_Name )
    {
        ResourceSet::iterator found = m_Resources.find( p_Name );
        if( found == m_Resources.end() )
        {
					
            return( ResourcePtr() );
        }

        ResourceWeakPtr wp = found->second;
        if( wp.expired() )
        {
            // remove it since its outdated.
            m_Resources.erase( found );
            return( ResourcePtr() );
        }
	

        // note: always give a weakptr a named ptr when converting (or so say's the spec :) )
        ResourcePtr p = wp.lock();
		

        return( p );
    }



}